<?php
/**
 * 用户通信录数理检查
 * User: csyr
 * Date: 16/6/28
 * Time: 下午10:23
 */

namespace Home\Common\Hook;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Log;

class ContactRestrictive extends BaseHook
{

    public function execute($data, $params = [])
        {
            $customerId = $data['id'];
            if ($customerId) {
                //通讯录人数<20
                $contactCount = D("CustomerContact")->where(['customer_id'=>$customerId])->count();
                Log::write("Customer contact:".$contactCount, Log::INFO);
                if ($contactCount < $params['min']) {
                    BusinessException::throwException(Constant::NO_ENOUGH_CONTACT);
                }

                //通讯录敏感词>=3
                $badwords = $params['badwords'];
                $add_sql = '';
                if($badwords) {
                    foreach($badwords as $v) {
                        $add_sql .=  "`contact_name` like '%".$v."%' or ";
                    }
                    $add_sql = substr($add_sql,0,-3);
                    $sql = "customer_id = '$customerId' and ($add_sql)";
                } else {
                    $sql = "customer_id = '$customerId'";
                }

                $badwordsCount = D("CustomerContact")->where($sql)->count();
                if ($badwordsCount >= $params['badwords_max']) {
                    BusinessException::throwException(Constant::NO_ENOUGH_CONTACT1);
                }

                //通讯录有效联系方式词数量<3
                $goodwords = $params['goodwords'];
                $add_sql = '';
                if($goodwords) {
                    foreach($goodwords as $v) {
                        $add_sql .=  "`contact_name` like '%".$v."%' or ";
                    }
                    $add_sql = substr($add_sql,0,-3);
                    $sql = "customer_id = '$customerId' and ($add_sql)";
                } else {
                    $sql = "customer_id = '$customerId'";
                }
                $goodwordsCount = D("CustomerContact")->where($sql)->count();
                if ($goodwordsCount < $params['goodwords_min']) {
                    BusinessException::throwException(Constant::NO_ENOUGH_CONTACT2);
                }

                //通讯录重复率 >50%
                $groupCountResult =D("CustomerContact")->query("SELECT COUNT( id ) AS count, `contact_name` FROM  `customer_contact` WHERE  `customer_id` ='$customerId' GROUP BY  `contact_phone` ORDER BY count DESC ");
                $groupCount = count($groupCountResult);
                //重复率大于50%
                if ( round($groupCount/$contactCount,3) <= $params['repetition_rate'] ) {
                    BusinessException::throwException(Constant::NO_ENOUGH_CONTACT3);
                }
            }
            return $data;
        }
} 
